package newsSystem.news;

import org.jdatepicker.impl.JDatePanelImpl;
import org.jdatepicker.impl.JDatePickerImpl;
import org.jdatepicker.impl.UtilDateModel;
import newsSystem.dao.NewsInfoJDBC;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

public class NewsEditJFrame extends JFrame {
    private JTextField newsIDField;
    private JTextField newsNameField;
    private JTextField newsPublishField;
    private JTextField mPriceField;
    private JTextField newsCNoField;
    private JTextField newsDeptField;
    private JTextField newsContentArea;
    private JDatePickerImpl datePicker;
    private JLabel imagePreviewLabel= new JLabel();
    private byte[] newsImage;
    private  Date newsDate;
    private EditCallback editCallback;
    //    定义一个接口
    // 定义回调接口
    public interface EditCallback {
        void onEditSuccess(NewsInfo updatedNews);
    }

    public NewsEditJFrame(NewsInfo news, EditCallback callback) {
        // 初始化窗口
        this.editCallback = callback;

        setTitle("报刊信息编辑");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(1000, 1000);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(20, 40, 15, 10);
        gbc.anchor = GridBagConstraints.WEST;

        // NewsName
        gbc.gridx = 0;
        gbc.gridy = 1;
        mainPanel.add(new JLabel("NewsID:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 1;
        newsIDField = new JTextField(23);
        newsIDField.setFont(new Font(Font.SERIF, Font.PLAIN, 12));
        newsIDField.setPreferredSize(new Dimension(23, 27)); // 设置文本框的宽度和高度
        mainPanel.add(newsIDField, gbc);
// NewsName
        gbc.gridx = 0;
        gbc.gridy = 2;
        mainPanel.add(new JLabel("NewsName:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 2;
        newsNameField = new JTextField(23);
        mainPanel.add(newsNameField, gbc);
        newsNameField.setFont(new Font(Font.SERIF, Font.PLAIN, 12));
        newsNameField.setPreferredSize(new Dimension(23, 27));
        mainPanel.add(newsNameField, gbc);

// NewsPublish
        gbc.gridx = 0;
        gbc.gridy = 3;
        mainPanel.add(new JLabel("NewsPublish:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 3;
        newsPublishField = new JTextField(23);
        newsPublishField.setFont(new Font(Font.SERIF, Font.PLAIN, 12));
        newsPublishField.setPreferredSize(new Dimension(23, 27));
        mainPanel.add(newsPublishField, gbc);

// MPrice
        gbc.gridx = 0;
        gbc.gridy = 4;
        mainPanel.add(new JLabel("MPrice:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 4;
        mPriceField = new JTextField(23);
        mPriceField.setFont(new Font(Font.SERIF, Font.PLAIN, 12));
        mPriceField.setPreferredSize(new Dimension(23, 27));
        mainPanel.add(mPriceField, gbc);

// NewsContent
// 不需要设置大小，因为它在JScrollPane中

// NewsDate
        gbc.gridx = 0;
        gbc.gridy = 5;
        mainPanel.add(new JLabel("NewsDate:"), gbc);

        // 创建一个UtilDateModel对象，它是JDatePickerImpl的数据模型

        // 创建一个UtilDateModel对象，它是JDatePickerImpl的数据模型
        UtilDateModel model = new UtilDateModel();

        // 创建一个Properties对象，用于指定日期格式
        Properties properties = new Properties();
        properties.put("text.today", "Today");
        properties.put("text.month", "Month");
        properties.put("text.year", "Year");

        // 创建JDatePanelImpl对象，它包含了日期选择器的界面
        JDatePanelImpl datePanel = new JDatePanelImpl(model, properties);

        // 创建JDatePickerImpl对象，并传入JDatePanelImpl对象
        datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter());
// 添加日期选择变化监听器
        datePicker.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String newsIDText = newsIDField.getText();
                System.out.println(newsIDText);
                // 获取选择的日期
                Date selectedDate = (Date) datePicker.getModel().getValue();
                // 更新 newsDate 变量
                newsDate = selectedDate;
            }
        });
        gbc.gridx = 1;
        gbc.gridy = 5;
        // 创建一个JDatePicker对象
        mainPanel.add(datePicker, gbc);

// NewsCNo
        gbc.gridx = 0;
        gbc.gridy = 6;
        mainPanel.add(new JLabel("NewsCNo:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 6;
        newsCNoField = new JTextField(23);
        newsCNoField.setFont(new Font(Font.SERIF, Font.PLAIN, 12));
        newsCNoField.setPreferredSize(new Dimension(23, 27));
        mainPanel.add(newsCNoField, gbc);

//// NewsImage
//// 注意：此处应使用文件选择器（如JFileChooser）而不是文本框来让用户选择图片
//// 下面的代码仅为演示，实际应用请替换为合适的图像选择组件
        gbc.gridx = 0;
        gbc.gridy = 7;
        JButton chooseImageButton = new JButton("选择图片");
        mainPanel.add(chooseImageButton, gbc);

        // 此处应放置一个按钮用来打开文件选择器，而非文本框
        gbc.gridx = 1;
        gbc.gridy = 7;


        mainPanel.add(imagePreviewLabel, gbc);
        // 设置图片预览标签的大小
        imagePreviewLabel.setPreferredSize(new Dimension(200, 100)); // 设置宽度和高度
        // 设置填充方式为填充容器
        gbc.fill = GridBagConstraints.BOTH;
        mainPanel.add(imagePreviewLabel, gbc);

        // 设置选择图片按钮的点击事件
        // 设置选择图片按钮的点击事件
        chooseImageButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 创建文件选择器
                JFileChooser fileChooser = new JFileChooser();
                // 设置文件选择器只能选择图片文件
                fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
                    public boolean accept(File f) {
                        return f.getName().toLowerCase().endsWith(".jpg") ||
                                f.getName().toLowerCase().endsWith(".jpeg") ||
                                f.getName().toLowerCase().endsWith(".png") ||
                                f.isDirectory();
                    }

                    public String getDescription() {
                        return "图片文件 (*.jpg, *.jpeg, *.png)";
                    }
                });

                // 显示文件选择器对话框
                Component frame = null;
                int result = fileChooser.showOpenDialog(frame);
                // 如果用户选择了文件
                if (result == JFileChooser.APPROVE_OPTION) {
                    // 获取用户选择的文件
                    File selectedFile = fileChooser.getSelectedFile();
                    try {
                        // 读取文件内容并存储为字节数组
                        newsImage = readImageFile(selectedFile);
                        System.out.println(newsImage);
                        // 设置图片预览
                        ImageIcon imageIcon = new ImageIcon(selectedFile.getPath());
                        imagePreviewLabel.setIcon(imageIcon);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(frame, "读取图片文件时发生错误");
                    }
                }
            }
        });



// NewsDept
        gbc.gridx = 0;
        gbc.gridy = 8;
        mainPanel.add(new JLabel("NewsDept:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 8;
        newsDeptField = new JTextField(23);
        newsDeptField.setFont(new Font(Font.SERIF, Font.PLAIN, 12));
        newsDeptField.setPreferredSize(new Dimension(23, 27));
        mainPanel.add(newsDeptField, gbc);

        // 添加 NewsContentArea
        gbc.gridx = 0;
        gbc.gridy = 9; // 假设 NewsContentArea 要放在第 9 行
        mainPanel.add(new JLabel("NewsContent:"), gbc);

        gbc.gridx = 1;
        gbc.gridy = 9;
        newsContentArea = new JTextField(23);
        newsContentArea.setFont(new Font(Font.SERIF, Font.PLAIN, 12));
        newsContentArea.setPreferredSize(new Dimension(20, 27));
        mainPanel.add(newsContentArea, gbc);

        // 创建按钮
        JButton editButton = new JButton("编辑");

        JButton cancleButton = new JButton("取消");
        editButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
//                editNewsInfo();
                editNewsInfo(news);
                System.out.println(newsImage);
            }
        });
        cancleButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 在按钮点击事件中关闭窗口
                Window window = SwingUtilities.getWindowAncestor(cancleButton); // 获取按钮所在的窗口
                if (window != null) {
                    window.dispose(); // 关闭窗口
                }
            }
        });
        gbc.gridx = 0;
        gbc.gridy = 10;
        gbc.gridwidth = 1;
        mainPanel.add(editButton, gbc);

//取消
        gbc.gridx = 2;
        gbc.gridy = 10;
        gbc.gridwidth = 2;
        mainPanel.add( cancleButton, gbc);


        // 填充文本框
        newsIDField.setText(String.valueOf(news.getNewsID()));
        newsNameField.setText(news.getNewsName());
        newsPublishField.setText(news.getNewsPublish());
        mPriceField.setText(String.valueOf(news.getMPrice()));
        newsContentArea.setText(news.getNewsContent());
        newsCNoField.setText(news.getNewsCNo());
        newsDeptField.setText(news.getNewsDept());
        newsImage = news.getNewsImage();
        newsDate = news.getNewsData();
        // 清空图片预览区域
//        imagePreviewLabel.setIcon(news.getNewsImage());
// 清空日期选择器中的日期
//        datePicker.getModel().setValue(news.getNewsData());


        // 将mainPanel设置为窗口的内容面板
        setContentPane(mainPanel);

        // 设置窗口大小和可见性
        setSize(500, 500);
        setLocationRelativeTo(null); // 居中显示
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 为了让窗口大小能够适应组件内容，调用pack()
        pack();

        // 设置窗口可见
        setVisible(true);
    }

//    编辑操作
private void editNewsInfo(NewsInfo newsInfo) {
    try {
        // 判断是否有必填字段为空
        if (newsNameField.getText().isEmpty() ||
                newsPublishField.getText().isEmpty() ||
                mPriceField.getText().isEmpty() ||
                newsContentArea.getText().isEmpty() ||
                newsCNoField.getText().isEmpty() ||
                newsDeptField.getText().isEmpty() ||
                newsImage == null ||
                newsDate == null) {
            // 弹出提示框
            JOptionPane.showMessageDialog(null, "请完善所有必填字段！", "提示", JOptionPane.WARNING_MESSAGE);
        } else {
            // 获取表单中的内容
            String newsName = newsNameField.getText();
            String newsPublish = newsPublishField.getText();
            double mPrice = Double.parseDouble(mPriceField.getText());
            String newsContent = newsContentArea.getText();
            String newsCNo = newsCNoField.getText();
            String newsDept = newsDeptField.getText();
            System.out.println(newsImage);
            System.out.println(newsDate);

            // 更新NewsInfo对象的属性
            newsInfo.setNewsName(newsName);
            newsInfo.setNewsPublish(newsPublish);
            newsInfo.setMPrice(mPrice);
            newsInfo.setNewsContent(newsContent);
            newsInfo.setNewsData(newsDate);
            newsInfo.setNewsCNo(newsCNo);
            newsInfo.setNewsImage(newsImage);
            newsInfo.setNewsDept(newsDept);

            // 可以将更新后的newsInfo对象存储到数据库中或进行其他操作
            System.out.println("News Info Updated: " + newsInfo.getNewsData());
            System.out.println("News Info Updated: " + newsInfo.getNewsPublish());
            System.out.println("News Info Updated: " + newsInfo.getNewsDept());
            System.out.println("News Info Updated: " + newsInfo.getNewsID());
            // 更新报刊信息到数据库中
            NewsInfoJDBC.updateNewsInDatabase(newsInfo);
            System.out.println("更新成功");
            // 通知编辑成功,进行通知主页面
            notifyEditSuccess(newsInfo);
            // 清空表单字段
            clearFields();
            // 关闭当前编辑窗口
            dispose();
        }
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(this, "Invalid input! Please enter valid data.", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

    //清空表单字段
    private void clearFields() {
        // 清空表单字段
        newsIDField.setText("");
        newsNameField.setText("");
        newsPublishField.setText("");
        mPriceField.setText("");
        newsContentArea.setText("");
        // 清空日期选择器中的日期
        datePicker.getModel().setValue(null);
        newsCNoField.setText("");
        newsDeptField.setText("");
        // 清空图片字段
        // 清空图片预览区域
        imagePreviewLabel.setIcon(null);
        // 清空日期选择器中的日期
        datePicker.getModel().setValue(null);
    }
    // 自定义的日期标签格式化器类
    static class DateLabelFormatter extends JFormattedTextField.AbstractFormatter {
        private String datePattern = "yyyy-MM-dd";
        private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);

        @Override
        public Object stringToValue(String text) throws ParseException {
            return dateFormatter.parseObject(text);
        }

        @Override
        public String valueToString(Object value) throws ParseException {
            if (value != null) {
                Calendar cal = (Calendar) value;
                return dateFormatter.format(cal.getTime());
            }

            return "";
        }
    }

    // 读取图片文件内容并返回字节数组
    private byte[] readImageFile(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        fis.read(buffer);
        fis.close();
        return buffer;

    }
    // 编辑成功后调用该方法通知主页面
    private void notifyEditSuccess(NewsInfo updatedNews) {
        if (editCallback != null) {
            editCallback.onEditSuccess(updatedNews);
        }
    }
}